<template>
  <div class="new-page table-h-48">
    <a-form-model layout="inline" :model="search" class="comm-search-f" :style="`width: calc(100% - ${sideMenuWidth} - 33px)`">

      <!-- 筛选条件与查询 -->
      <!-- 故障码 -->
      <a-form-model-item label="">
        <a-input
          v-model="search.keyword"
          placeholder="关键字"
        />
      </a-form-model-item>
      <a-form-model-item label="">
        <a-select
          v-model="search.roleId"
          show-arrow
          style="width: 100%"
          mode="multiple"
          placeholder="角色"
          allow-clear
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="item in roleAll" :key="item.name" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>

      </a-form-model-item>
      <a-form-model-item label="">
        <tailNumber
          v-model="search.tailnumber"
          value-key="tailnumber"
          name-key="tailnumber"
          width="100%"
        />
      </a-form-model-item>
      <!-- 故障码 -->

      <!-- 是否发送邮邮件或sms -->
      <a-form-model-item style="flex-basis:18%!important">
        <a-button type="default" ghost :loading="userListLoading" @click="resetSearchHandler">
          重置
        </a-button>
        <a-button class="ml-12" type="primary" :loading="userListLoading" @click="changeTable({ current: 1 })">
          查询
        </a-button>

      </a-form-model-item>
    </a-form-model>

    <a-table

      :columns="columns"
      size="middle"
      :data-source="userList"
      :row-key="(row,index) => row.id"
      :pagination="{
        showTotal:(total)=> `共 ${total} 条数据`,
        showSizeChanger: true,//设置每页显示数据条数
        showQuickJumper: true,
        size:'big',
        current:paginationOptions.pageNum,
        pageSize:paginationOptions.pageSize,
        total:paginationOptions.total
      }"
      :loading="userListLoading"
      @change="changeTable"
    />

    <a-modal
      v-model="setRoleVisible"
      :mask-closable="false"
      title=""
      :confirm-loading="addLoading"
      :width="400"
      class="rt-i-modal"
      :dialog-style="{height:'335px'}"
      centered
      @ok="setConfirmHandler"
      @cancel="setCancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">分配角色</div>
      <a-form-model
        ref="addForm"
        layout="horizontal"
      >
        <a-form-model-item prop="roleIds">
          <a-select
            v-model="addForm.roleIds"
            show-arrow
            style="width: 100%"
            class="input-type-o"
            placeholder="角色"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="item in roleAll" :key="item.name" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- add -->
    <a-modal
      v-model="jhVisible"
      :mask-closable="false"
      title=""
      :confirm-loading="jhLoading"
      :width="400"
      class="rt-i-modal"
      :dialog-style="{height:'500px'}"
      centered
      @ok="jhConfirmHandler"
      @cancel="jhCancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">分配机号</div>
      <a-form-model
        ref="jhAddForm"
        :model="jhAddForm"
        :rules="jhAddRules"
        layout="horizontal"
      >
        <a-form-model-item label="用户名" prop="username">

          <a-input
            v-model="jhAddForm.username"
            class="input-type-o"
            placeholder="用户名"
            disabled
          />
        </a-form-model-item>
        <a-form-model-item label="机队" prop="fleet">
          <a-select
            v-model="jhAddForm.fleet"
            style="minWidth: 100%"
            class="input-type-o"
            show-arrow
            allow-clear
            placeholder="机队"
            @change="changeFleetHandler"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in ftmFleetFindAllData" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="机号" prop="tailnumber">
          <a-select
            v-model="jhAddForm.tailnumber"
            style="minWidth: 100%"
            class="input-type-o"
            show-arrow
            mode="multiple"
            :max-tag-count="3"
            placeholder="机号"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <div slot="dropdownRender" slot-scope="menu">
              <div class="cus-all-check-box">
                <a-checkbox :checked="tailnumberAll" @change="onChangeChecked">
                  全选
                </a-checkbox>
              </div>
              <v-nodes :vnodes="menu" />
            </div>
            <a-select-option v-for="selectItem in findListByFleetData" :key="selectItem.id" :value="selectItem.tailnumber">
              {{ selectItem.tailnumber }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapActions, mapGetters, mapState, mapMutations } from 'vuex';
import tailNumber from '@/pages/components/tailNumber';
export default {
  components: {
    tailNumber,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  data() {
    return {
      search: {},
      setRoleVisible: false,
      addForm: {},
      jhVisible: false,
      addRow: {},
      jhAddForm: {
        username: '',
        fleet: '',
        tailnumber: []
      },
      jhAddRules: Object.freeze({
        username: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        tailnumber: [
          { required: true, type: 'array', message: '请选择', trigger: 'change' }
        ],
        fleet: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }),
      columns: Object.freeze([
        {
          title: '用户名',
          align: 'left',
          dataIndex: 'username',
          customRender: (value, record) => {
            return value || '--';
          }
        },
        {
          title: '邮箱',
          align: 'left',
          dataIndex: 'email',
          customRender: (value, record) => {
            return value || '--';
          }
        },
        {
          title: '所属角色',
          align: 'left',
          dataIndex: 'name',
          customRender: (value, record) => {
            return value || '--';
          }
        },
        {
          title: '拥有机号',
          align: 'left',
          width: 700,
          dataIndex: 'tailnumber',
          ellipsis: true,
          customRender: (value, record) => {
            if (value?.length > 5) {
              return <a-tooltip placement='bottomLeft'>
                <template slot='title'>
                  {(value ?? ['--']).join()}
                </template>
                {(value ?? ['--']).join()}
              </a-tooltip>;
            }
            return (value ?? ['--']).join();
          }
        },
        // {
        //   title: '创建时间',
        //   align: 'left',
        //   dataIndex: 'createTime',
        //   customRender: (value, record) => {
        //     return value ? this.$moment.utc(value) : '--';
        //   }
        // },
        // {
        //   title: '更新时间',
        //   align: 'left',
        //   dataIndex: 'updateTime',
        //   customRender: (value, record) => {
        //     return value ? this.$moment.utc(value) : '--';
        //   }
        // },
        // {
        //   title: '最后登录时间',
        //   align: 'left',
        //   dataIndex: 'lastTime',
        //   customRender: (value, record) => {
        //     return value ? this.$moment.utc(value) : '--';
        //   }
        // },
        {
          title: '操作',
          align: 'left',
          dataIndex: 'option',
          width: 180,
          customRender: (value, record, index) => {
            return [

              <a-button type='link' onClick={() => this.setRoleHandler(record, index)}>分配角色</a-button>,
              <a-button type='link' onClick={() => this.setJHHandler(record, index)}>分配机号</a-button>
              // <a-button type='primary' size='small' ghost>版本管理</a-button>
            ];
          }
        }
      ])
    };
  },
  computed: {
    ...mapState('users', [
      'userList',
      'userListLoading',
      'paginationOptions',
      'roleAll',
      'addLoading',
      'userRoles',
      'jhLoading',
      'findListByFleetLoading',
      'findListByFleetData',
      'ftmFleetFindAllLoading',
      'ftmFleetFindAllData'
    ]),
    ...mapState('fraMonitoring', [
      'ftmAirplaneList'
    ]),
    ...mapState('userAirplaneRelation', [
      'tailNumberAndFleetUserName'
    ]),
    tailnumberAll() {
      if (this.findListByFleetData.length) {
        return this.findListByFleetData.length === this.jhAddForm?.tailnumber?.length ?? 0;
      } else {
        return false;
      }
    },
    ...mapGetters('setting', ['sideMenuWidth'])
  },
  mounted() {
    this.changeTable({ current: 1 });
    this.getRoleAll();
    this.ftmFleetFindAll();
  },
  methods: {
    ...mapMutations('users', [
      'setState'
    ]),
    ...mapActions('users', [
      'getListUser',
      'getRoleAll',
      'addUserRoleRelation',
      'getRoleByUserId',
      'findListByFleet',
      'ftmFleetFindAll'
    ]),

    ...mapActions('userAirplaneRelation', [
      'getTailNumberAndFleet',
      'addlistUserAirplanRelation'
    ]),
    changeTable({ current, pageSize = 10 }) {
      if (pageSize !== this.paginationOptions.pageSize) {
        current = 1;
      }
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getListUser(this.search);
    },
    async setRoleHandler(row) {
      await this.getRoleByUserId({ userId: row.id });
      this.addRow = { ...row };
      this.setRoleVisible = true;
      this.addForm = {
        roleIds: this.userRoles.roleId
      };
    },
    // 重置
    resetSearchHandler() {
      this.search = {};
      this.changeTable({ current: 1 });
    },
    // 设置权限
    setConfirmHandler() {
      const params = {
        userId: this.addRow.id,
        roleIds: this.addForm.roleIds
      };
      this.addUserRoleRelation(params).then((rep) => {
        if (rep) {
          this.changeTable({ current: 1 });
          this.setRoleVisible = false;
        }
      });
    },
    onChangeChecked(v) {
      if (v.target.checked) {
        this.$set(this.jhAddForm, 'tailnumber', this.findListByFleetData.map(item => item.tailnumber));
      } else {
        this.$set(this.jhAddForm, 'tailnumber', []);
      }
    },
    // 设置权限
    setCancelHandler() {
      this.addForm = {};
      this.addTitle = '新增';
      this.$refs.addForm.resetFields();
    },
    changeFleetHandler(fleet) {
      if (fleet !== this.tailNumberAndFleetUserName[0]?.fleet) {
        this.jhAddForm.tailnumber = [];
      } else {
        this.jhAddForm.tailnumber = this.tailNumberAndFleetUserName[0]?.tailNumber ?? [];
      }

      this.findListByFleet({ fleet });
    },
    async setJHHandler(row) {
      this.jhVisible = true;

      await this.getTailNumberAndFleet({ userName: row.username });
      if (this.tailNumberAndFleetUserName[0]) {
        const { fleet, tailNumber } = this.tailNumberAndFleetUserName[0];
        this.findListByFleet({ fleet });
        this.jhAddForm = { ...row, fleet, tailnumber: tailNumber };
      } else {
        this.jhAddForm = { ...row, tailnumber: [] };
      }
    },
    jhConfirmHandler() {
      this.$refs.jhAddForm.validate(valid => {
        if (valid) {
          const params = {
            username: this.jhAddForm.username,
            tailNumberAndFleets: [{
              fleet: this.jhAddForm.fleet,
              tailNumber: this.jhAddForm.tailnumber
            }]
          };

          this.addlistUserAirplanRelation(params).then((rep) => {
            if (rep) {
              this.jhCancelHandler();
              this.changeTable({ current: 1 });
            }
          });
        } else {
          return false;
        }
      });
    },
    jhCancelHandler() {
      this.jhVisible = false;
      this.jhAddForm = {
        username: '',
        fleet: '',
        tailnumber: []
      };
      this.$refs.jhAddForm.resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
.cus-all-check-box{
padding: 12px 12px 0;
  .ant-checkbox-wrapper{
    /deep/span:nth-last-child(1){
      padding-left: 4px;
    }
  }
}
</style>
